<template>
  <view>
    <web-view
      v-if="webviewStyles.height"
      ref="webViewRef"
      allow
      :update-title="false"
      :src="srcUrl"
      :webview-styles="webviewStyles"
      @message="onMessage"
    ></web-view>
    <view v-show="visible" class="btn-fence-group" style="">
      <view class="btn-fence" @click="handleClear()">清除绘制</view>
      <view class="btn-fence" @click="handleSubmit()">保存</view>
    </view>
  </view>
</template>
<script>
import { staticUrl } from '@/config'
import { getToken } from '@/utils/auth'
import { uploadBase64Request } from '@/api/file/upload'

export default {
  data() {
    return {
      srcUrl: staticUrl + '/basic-product/cesium/uni-app?token=' + getToken(),
      webviewStyles: {},
      visible: false,
      saveLoading: false,
      isDrawEnd: true,
      fenceData: {}
    }
  },
  onLoad() {
    uni.getSystemInfo({
      success: (e) => {
        this.webviewStyles.height = e.windowHeight - 50 + 'px'
        this.webviewStyles.width = e.windowWidth + 'px'
      }
    })
    // #ifdef APP-PLUS
    const currentWebview = this.$scope.$getAppWebview()
    setTimeout(() => {
      this.wv = currentWebview.children()[0]
      this.wv.setStyle({ bottom: '50px' })
      if (this.afterFunc) {
        this.createArea()
        this.afterFunc = false
      }
    }, 1000) //如果是页面初始化调用时，需要延时一下
    // #endif

    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('fenceData', (data) => {
      this.originalData = data
      this.fenceData = {
        coordinates: [data.electronicFenceCoordinates],
        extrudedHeight: [data.electronicFenceExtrudeHeight],
        height: [data.electronicFenceHeight],
        image: data.electronicFenceImage
      }
    })
  },
  methods: {
    createArea() {
      let location = ''
      if (this.originalData && this.originalData.electronicFenceCoordinates.length) {
        location = {
          coordinates: [this.originalData.electronicFenceCoordinates],
          extrudedHeight: [this.originalData.electronicFenceExtrudeHeight],
          height: [this.originalData.electronicFenceHeight]
        }
        console.log('location', location)
      }
      const evalStr = `uniAppFunc('${JSON.stringify({
        type: 'area',
        data: { location: location, readonly: false, color: '#ff0000' }
      })}')`
      console.log('evalStr', evalStr)
      this.wv.evalJS(evalStr)
    },
    onMessage(data) {
      const { action, msg } = data?.detail?.data[0]

      console.log('onMessage action', action)
      console.log('onMessage msg', msg)

      switch (action) {
        case 'ready':
          if (!this.wv) {
            this.afterFunc = true
          } else {
            this.createArea()
          }
          this.visible = true
          break
        case 'change':
          this.onChange(msg)
          break
        default:
          break
      }
    },
    async onChange(data) {
      this.fenceData = data.data ? JSON.parse(data.data) : {}
      this.fenceData.image = data.image ?? ''
      console.log('this.fenceData', this.fenceData)
    },
    back(data) {
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('fence:form:success', JSON.parse(JSON.stringify(data)))
      uni.navigateBack()
    },
    handleClear() {
      this.wv.evalJS(
        `uniAppFunc('${JSON.stringify({
          type: 'clear'
        })}')`
      )
    },
    // fix: 11755 绘制电子围栏还没渲染出来红框 就点了保存，导致未显示围栏
    rerenderImage() {
      this.wv.evalJS(
        `uniAppFunc('${JSON.stringify({
          type: 'getData'
        })}')`
      )
    },
    async handleSubmit() {
      if (this.saveLoading) {
        return
      }
      uni.showLoading({
        title: '加载中'
      })
      setTimeout(() => {
        this.rerenderImage()
        uni.hideLoading()
        uni.showModal({
          title: '提示',
          content: '确认保存当前绘制的围栏？',
          success: async (res) => {
            if (res.confirm) {
              if (this.fenceData.image.indexOf('data:image/') > -1) {
                uni.showLoading({
                  title: '正在保存'
                })
                this.saveLoading = true
                const res = await uploadBase64Request(this.fenceData.image).finally(() => {
                  this.saveLoading = false
                  uni.hideLoading()
                })
                const path = res.data.relativeUrl
                this.fenceData.image = path
              }
              this.back(this.fenceData)
            }
          }
        })
      }, 2000)
    }
  }
}
</script>
<style scoped lang="scss">
.btn-fence-group {
  height: 50px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  background: #fff;
  .btn-fence {
    flex: 1;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 32rpx;
    border-right: 1rpx solid #efefef;
  }
}
</style>
